from flask import Flask, request, jsonify
import os
import requests
import json
import logging
from dotenv import load_dotenv

# 配置日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("debug.log"),
        logging.StreamHandler()
    ]
)

# 加载环境变量
load_dotenv()

# Jina AI API配置
JINA_API_KEY = os.getenv("JINA_API_KEY", "jina_b8e7dd0e5f7a45ecb03429f5dcc5de92ZREJN73p43A6UNZ5jsnjm7PnCT7A")
JINA_API_URL = "https://deepsearch.jina.ai/v1/chat/completions"

app = Flask(__name__, static_folder='static')

@app.route('/')
def index():
    return app.send_static_file('index.html')

@app.route('/<path:path>')
def static_file(path):
    try:
        return app.send_static_file(path)
    except:
        # 如果找不到文件，返回index.html
        return app.send_static_file('index.html')

@app.route('/api/translate', methods=['POST'])
def translate():
    data = request.json
    text = data.get('text', '')
    source_lang = data.get('source_lang', 'auto')
    target_lang = data.get('target_lang', 'en')
    
    if not text:
        return jsonify({"error": "No text provided"}), 400
    
    try:
        # 打印请求信息，便于调试
        print(f"翻译请求: 文本='{text}', 源语言={source_lang}, 目标语言={target_lang}")
        
        # 准备请求头
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {JINA_API_KEY}"
        }
        
        # 准备请求数据
        request_data = {
            "model": "jina-deepsearch-v1",
            "messages": [
                {
                    "role": "system",
                    "content": f"You are a professional translator. Translate the following text from {source_lang} to {target_lang}. Only provide the translation without any explanations or additional text."
                },
                {
                    "role": "user",
                    "content": text
                }
            ],
            "stream": False,
            "reasoning_effort": "medium",
            "max_attempts": 1,
            "no_direct_answer": False
        }
        
        print(f"发送请求到 {JINA_API_URL}")
        print(f"请求数据: {json.dumps(request_data, ensure_ascii=False)}")
        
        # 调用Jina AI API
        response = requests.post(JINA_API_URL, headers=headers, json=request_data)
        
        # 打印响应状态和内容
        print(f"API响应状态码: {response.status_code}")
        print(f"API响应内容: {response.text[:500]}...")  # 只打印前500个字符
        
        response.raise_for_status()  # 检查HTTP错误
        
        # 解析响应
        response_data = response.json()
        translated_text = response_data.get('choices', [{}])[0].get('message', {}).get('content', '').strip()
        
        if not translated_text:
            raise Exception("No translation received from API")
        
        print(f"翻译结果: '{translated_text}'")
        
        return jsonify({
            "translated_text": translated_text,
            "model_used": "jina-deepsearch-v1",
            "source_lang": source_lang,
            "target_lang": target_lang
        })
    
    except requests.exceptions.RequestException as e:
        print(f"API请求错误: {str(e)}")
        if hasattr(e, 'response') and e.response:
            print(f"错误响应: {e.response.text}")
        return jsonify({"error": f"API请求错误: {str(e)}"}), 500
    except Exception as e:
        import traceback
        print(f"翻译错误: {str(e)}")
        print(traceback.format_exc())  # 打印完整的堆栈跟踪
        return jsonify({"error": str(e)}), 500

@app.route('/api/translate/contextual', methods=['POST'])
def contextual_translate():
    data = request.json
    text = data.get('text', '')
    context = data.get('context', '')
    source_lang = data.get('source_lang', 'auto')
    target_lang = data.get('target_lang', 'en')
    
    if not text:
        return jsonify({"error": "No text provided"}), 400
    
    if not context:
        return jsonify({"error": "No context provided"}), 400
    
    try:
        # 打印请求信息，便于调试
        print(f"情境化翻译请求: 文本='{text}', 上下文='{context}', 源语言={source_lang}, 目标语言={target_lang}")
        
        # 准备请求头
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {JINA_API_KEY}"
        }
        
        # 准备请求数据
        request_data = {
            "model": "jina-deepsearch-v1",
            "messages": [
                {
                    "role": "system",
                    "content": f"You are a professional translator with cultural expertise. Translate the following text from {source_lang} to {target_lang}, considering the provided context. Your response must follow this exact format:\n\nLiteral translation: [literal translation]\n\nContextual translation: [contextual translation]\n\n- [alternative expression 1]\n- [alternative expression 2]\n- [alternative expression 3]\n\nCultural notes: [cultural notes and background information]"
                },
                {
                    "role": "user",
                    "content": f"Text to translate: {text}\nContext: {context}"
                }
            ],
            "stream": False,
            "reasoning_effort": "high",  # 使用高级推理以获得更好的结果
            "max_attempts": 1,
            "no_direct_answer": False
        }
        
        print(f"发送请求到 {JINA_API_URL}")
        print(f"请求数据: {json.dumps(request_data, ensure_ascii=False)}")
        
        # 调用Jina AI API
        response = requests.post(JINA_API_URL, headers=headers, json=request_data)
        
        # 打印响应状态和内容
        print(f"API响应状态码: {response.status_code}")
        print(f"API响应内容: {response.text[:500]}...")  # 只打印前500个字符
        
        response.raise_for_status()  # 检查HTTP错误
        
        # 解析响应
        response_data = response.json()
        result = response_data.get('choices', [{}])[0].get('message', {}).get('content', '').strip()
        
        if not result:
            raise Exception("No translation received from API")
        
        print(f"翻译结果: '{result[:100]}...'")  # 只打印前100个字符
        
        # 解析结果
        parts = result.split("\n\n")
        literal = parts[0].replace("Literal translation: ", "") if len(parts) > 0 else "未提供直译"
        contextual = parts[1].replace("Contextual translation: ", "") if len(parts) > 1 else "未提供情境化翻译"
        
        alternatives = []
        if len(parts) > 2:
            alt_section = parts[2].split("\n")
            for alt in alt_section:
                if alt.startswith("- "):
                    alternatives.append(alt[2:])
        
        cultural_notes = parts[3].replace("Cultural notes: ", "") if len(parts) > 3 else "未提供文化注释"
        
        return jsonify({
            "translations": {
                "literal": literal,
                "contextual": contextual,
                "alternatives": alternatives,
                "cultural_notes": cultural_notes
            },
            "model_used": "jina-deepsearch-v1",
            "source_lang": source_lang,
            "target_lang": target_lang
        })
    
    except requests.exceptions.RequestException as e:
        print(f"API请求错误: {str(e)}")
        if hasattr(e, 'response') and e.response:
            print(f"错误响应: {e.response.text}")
        return jsonify({"error": f"API请求错误: {str(e)}"}), 500
    except Exception as e:
        import traceback
        print(f"情境化翻译错误: {str(e)}")
        print(traceback.format_exc())  # 打印完整的堆栈跟踪
        return jsonify({"error": str(e)}), 500

@app.errorhandler(404)
def page_not_found(e):
    # 处理所有404错误，返回index.html
    return app.send_static_file('index.html')

# 添加一个简单的测试端点，用于验证API连接
@app.route('/api/test', methods=['GET'])
def test_api():
    try:
        # 准备请求头
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {JINA_API_KEY}"
        }
        
        # 准备简单的请求数据
        request_data = {
            "model": "jina-deepsearch-v1",
            "messages": [
                {
                    "role": "user",
                    "content": "Hello"
                }
            ],
            "stream": False,
            "max_attempts": 1
        }
        
        print("发送测试请求到Jina API...")
        
        # 调用Jina AI API
        response = requests.post(JINA_API_URL, headers=headers, json=request_data)
        
        # 打印响应状态和内容
        print(f"API测试响应状态码: {response.status_code}")
        print(f"API测试响应内容: {response.text}")
        
        if response.status_code == 200:
            return jsonify({"status": "success", "message": "API连接正常", "response": response.json()}), 200
        else:
            return jsonify({"status": "error", "message": f"API返回错误状态码: {response.status_code}", "response": response.text}), 500
    
    except Exception as e:
        import traceback
        print(f"API测试错误: {str(e)}")
        print(traceback.format_exc())
        return jsonify({"status": "error", "message": str(e)}), 500

if __name__ == '__main__':
    # 启动前测试API连接
    print(f"使用API密钥: {JINA_API_KEY[:10]}...")
    print(f"API URL: {JINA_API_URL}")
    
    app.run(debug=True, port=5000)